<?php
class NCategory extends NActiveRecord
{
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return '{{category}}';
    }

    public function rules()
    {
        return array(
            array('name', 'required'),
            array('name', 'length', 'max' => 20),
            array('ord', 'numerical', 'integerOnly' => true, 'min' => 0, 'max' => 255),
        );
    }

    public function  attributeLabels() {
        return array(
            'name' => '分类名称'
        );
    }

    public function relations()
    {
        return array(
            'items' => array(self::HAS_MANY, 'NItem', 'cid', 'order' => 'ord desc'),
        );
    }

    protected function afterSave()
    {
        if ($this->isNewRecord) {
            $this->upOrd();
        }
    }

    protected function afterDelete()
    {
        $this->upOrd();
    }

    public function upOrd()
    {
        $models = $this->findAll(array(
            'select' => 'id, ord',
            'order' => 'ord asc',
        ));

        foreach ($models as $key=>$model) {
            $model->ord = $key + 1;
            $model->update(array('ord'));
        }
    }

    public function setOrd($ord, $up = false)
    {
        $new = $up ? $ord+1 : $ord-1;
        try {
            $replaceModel = $this->findByAttributes(array('ord' => $new));
            $currentModel = $this->findByAttributes(array('ord' => $ord));
            if (null === $currentModel || null === $replaceModel)
                throw new Exception("没有能够找到替换的对象");
            $currentModel->ord = $new;
            $replaceModel->ord = $ord;
            $currentModel->update(array('ord'));
            $replaceModel->update(array('ord'));
        } catch (Exception $e) {
            return false;
        }
        return true;
    }
}